package middle

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"golang.org/x/text/encoding/simplifiedchinese"
	"DCOS-API/utils"
)

// IP查询归属地
type ipDetails struct {
	IP   string `json:"ip"`
	Pro  string `json:"pro"`
	City string `json:"city"`
	Err  string `json:"err"`
}

func IPFilter() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		ip := ctx.ClientIP()
		url := fmt.Sprintf("http://whois.pconline.com.cn/ipJson.jsp?ip=%v&json=true", ip)
		dataByte, _ := utils.GET(url, nil, nil)
		dataByte, _ = simplifiedchinese.GB18030.NewDecoder().Bytes(dataByte)
		ipDetails := new(ipDetails)
		_ = json.Unmarshal(dataByte, ipDetails)
		ctx.Set("pro", ipDetails.Pro)
		ctx.Set("city", ipDetails.City)
		ctx.Next()
	}
}
